<template>
	<el-row type="flex" justify="center">

		<el-col :span="6">

			<el-form label-position="right" :rules="rules" label-width="80px" :model="loginForm" ref="loginForm">
				<h1>商城后台管理系统登录</h1>
				<br>
				<el-form-item label="管理员名" prop="admin_name" style="width: 360px;">
					<el-input v-model="loginForm.admin_name"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="admin_password" style="width: 360px;">
					<el-input type="password" v-model="loginForm.admin_password"></el-input>
				</el-form-item>
				<el-form-item label="验证码" prop="code" style="width: 360px;">
					<el-input v-model="loginForm.code" style="width: 170px; float: left;" maxlength="5"></el-input>
					<el-image class="captchaImg" :src="captchaImg" @click="getCaptcha()"></el-image>
				</el-form-item>
				<el-form-item class="button">
					<el-button type="primary" @click="login('loginForm')">登录</el-button>
					<el-button type="primary" @click="reset('loginForm')">重置</el-button>
				</el-form-item>
			</el-form>
		</el-col>
	</el-row>
</template>
<script type="text/javascript">
	import qs from 'qs'
	export default {
		name: "Login",
		data() {
			return {
				loginForm: {
					admin_name: '',
					admin_password: '',
					code: '',
					token: '',
				},
				rules: {
					admin_name: [{
						required: true,
						message: '请输入管理员名',
						trigger: 'blur'
					}],
					admin_password: [{
						required: true,
						message: '请输入密码',
						trigger: 'blur'
					}],
					code: [{
							required: true,
							message: '请输入验证码',
							trigger: 'blur'
						},
						{
							min: 5,
							max: 5,
							message: '验证码为5个字符',
							trigger: 'blur'
						}
					],
				},
				captchaImg: null
			}
		},
		methods: {
			login(form) {
				this.$refs[form].validate((valid) => {
					if (valid) {
						this.$axios.post('/login', this.loginForm).then(res => {
							//自定义头 
							const jwt=res.headers['authorization']
							// 提交数据
							this.$store.commit('SET_TOKEN',jwt)
							
							this.$router.push("/")
						})
					} else {
						// alert("false");
						return false;
					}
				});
			},
			reset(form) {
				this.$refs[form].resetFields();
			},

			getCaptcha() {
			            this.$axios.get('/captcha').then(res => {
							console.log("/captcha");
							console.log(res);
			               this.loginForm.token = res.data.data.token
			               this.captchaImg = res.data.data.captchaImg
			            })
			         }
		},
      created() {
         this.getCaptcha()
      }
	}
</script>


<style scoped>
	.button .el-button {
		float: left;
		margin-left: 11%;
	}

	.el-col {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		text-align: center;
		margin-top: -60px;
	}

	.el-row {
		height: 100vh;
		background-color: ghostwhite;
	}

	.captchaImg {
		width: 100px;
		float: left;
		margin-left: 10px;
		border-radius: 4px;
		height: 40px;
	}
</style>
